<template>
  <a-form :form="formFee" layout="inline">
    <a-row style="width: 900px; margin: 0 auto">
      <a-col :span="12">
        <a-form-item label="提成规则" class="label">
          <a-select
            v-decorator="['saleRulesId']"
            :disabled="disabled"
            :options="ruleLst"
            :getPopupContainer="(triggerNode) => triggerNode.parentNode"
            placeholder="请选择"
            style="width: 260px"
          />
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="所属销售" class="label">
          <a-select
            v-decorator="['saleUserList', { rules: [{ required: isRequired, message: '必须选择所属销售' }] }]"
            :disabled="disabled"
            :options="saleLst"
            :getPopupContainer="(triggerNode) => triggerNode.parentNode"
            mode="multiple"
            placeholder="请选择"
            style="width: 260px"
            @change="onSaleChange"
          />
        </a-form-item>
      </a-col>
      <a-col v-show="formFee.getFieldValue('keys').length > 1" :span="24">
        <a-form-item label="分成比例" class="label" />
        <a-form-item v-for="k in formFee.getFieldValue('keys')" :key="k" :label="saleMap[k]['saleName']">
          <a-input
            v-decorator="[
              `names[${k}]`,
              {
                initialValue: keyIdValueMap[k] ? keyIdValueMap[k].value : undefined,
                rules: [{ required: true, message: '必须填写' }]
              }
            ]"
            :disabled="disabled"
            suffix="%"
            style="width: 70px"
          />
        </a-form-item>
      </a-col>
    </a-row>
  </a-form>
</template>
<script>
import request from "@/utils/request";
export default {
  name: "",
  components: {},
  mixins: [],
  props: {
    value: {
      type: Object,
      default: () => {}
    },
    companyId: {
      type: String,
      default: ""
    },
    isRequired: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      ruleLst: [],
      saleLst: [],
      saleMap: {},
      keyIdValueMap: {},
      relLoaded: false
    };
  },
  computed: {},
  watch: {
    value: {
      handler(newVal) {
        this.fillValues(newVal, this.relLoaded);
      },
      immediate: true
    },
    relLoaded(newVal) {
      this.fillValues(this.value, newVal);
    }
  },
  beforeCreate() {
    this.formFee = this.$form.createForm(this);
    this.formFee.getFieldDecorator("keys", { initialValue: [], preserve: true });
  },
  async created() {
    this.loadRules();
    await this.loadSales();
    this.relLoaded = true;
  },
  mounted() {},
  methods: {
    fillValues(theValue, loaded) {
      if (this.companyId && theValue && loaded) {
        if (theValue.saleRulesId) {
          this.formFee.setFieldsValue({
            saleRulesId: theValue.saleRulesId
          });
        }
        if (theValue.saleUserList && theValue.saleUserList.length > 0) {
          const keys = [];
          const names = {};
          for (let i = 0; i < theValue.saleUserList.length; i++) {
            keys.push(theValue.saleUserList[i].saleUserId);
            names[theValue.saleUserList[i].saleUserId] = {
              id: theValue.saleUserList[i].id,
              value: theValue.saleUserList[i].dividedProportion
            };
          }
          this.keyIdValueMap = names;
          this.formFee.setFieldsValue({
            saleUserList: keys,
            keys
          });
        }
      }
    },
    getValues() {
      return new Promise((resolve, reject) => {
        this.formFee.validateFields((err, values) => {
          if (err) {
            reject(false);
          } else {
            const saleUserList = values.keys.map((key) => {
              const newItem = {};
              if (this.companyId) {
                newItem["companyId"] = this.companyId;
              }
              newItem["dividedProportion"] = values.names[key];
              newItem["saleUserId"] = key;
              newItem["saleName"] = this.saleMap[key].saleName;
              if (this.keyIdValueMap[key]) {
                newItem["id"] = this.keyIdValueMap[key].id;
              }
              return newItem;
            });
            resolve({
              saleRulesId: values.saleRulesId,
              saleUserList
            });
          }
        });
      });
    },
    onSaleChange(selectedKeys) {
      this.updateItems(selectedKeys);
    },
    updateItems(ids) {
      this.formFee.setFieldsValue({
        keys: ids
      });
      if (ids.length === 1) {
        this.keyIdValueMap = {
          [`${ids[0]}`]: {
            id: ids[0],
            value: 100
          }
        };
      } else {
        this.keyIdValueMap = {};
      }
    },
    loadRules() {
      request({
        url: `/hr/api/v1/saleRebatesRules/selectSiteRebatesRules`,
        method: "get"
      })
        .then((res) => {
          this.ruleLst = res.data.map((item) => ({
            label: item.rulesName,
            value: item.id
          }));
        })
        .catch((err) => {
          console.log(err);
        });
    },
    async loadSales() {
      await request({
        url: `/hr/api/v1/saleUsers/selectSaleBySite`,
        method: "get"
      })
        .then((res) => {
          const tempMap = {};
          const tempArr = [];
          for (let i = 0; i < res.data.length; i++) {
            const item = res.data[i];
            tempArr.push({
              label: item.saleName,
              value: item.saleUserId
            });
            tempMap[item.saleUserId] = item;
          }
          this.saleMap = tempMap;
          this.saleLst = tempArr;
        })
        .catch((err) => {
          console.log(err);
        });
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep .label > .ant-form-item-label {
  width: 150px;
  text-align: right;
}
</style>
